<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class WordController extends Controller
{
    public function trans(Request $request)
    {
        $word = $request->input('word');
        $filename = $this->getFilename($word);
        
        $trans = '';
        if (\Storage::exists($filename)) {
            $trans = \Storage::get($filename);
        }

        return response()->json([
            'trans' => $trans
        ]);
    }

    public function create()
    {
        return view('words.create');
    }

    public function store(Request $request)
    {
        $word = $request->post('word');
        $trans = $request->post('trans');

        $filename = $this->getFilename($word);
        \Storage::put($filename, $trans);
        \Session::flash('message', '保存成功');
        return \redirect(route('words.create'));
    }

    private function getFilename(string $word)
    {
        return 'words/' . \strtolower($word);
    }
}
